<template>
    <div style="padding-left: 20px; padding-right: 20px; padding-top: 20px">
        <el-card class="box-card" shadow="never">
            <div slot="header" class="clearfix">
                <header-toolbar :buttons="['save', 'back', 'print']" @delete="handleDelete" @refresh="handleRefresh"
                    @save="handleSave" :objectId.sync="productPrice.id" @back="handleReturnList"
                    @print="handlePrint"></header-toolbar>
            </div>
            <div class="text item">
                <el-form :model="productPrice" :rules="headerRules" ref="form" label-width="100px"
                    label-position="rigth">
                    <el-row>
                        <el-col :span="6">
                            <el-form-item label="编码" prop="code">
                                <el-input v-model="productPrice.code"></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="6">
                            <el-form-item label="名称" prop="name">
                                <el-input v-model="productPrice.name"></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="6">
                            <el-form-item label="客户" prop="supplierId">
                                <supplier-select v-model="productPrice.supplierId" @change="handleSupplierChange">
                                </supplier-select>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-col :span="6">
                            <el-form-item label="币别" prop="currencyId">
                                <currency-select v-model="productPrice.currencyId" placeholder="请选择币别"
                                    @change="handleChangeCurrency">
                                </currency-select>
                            </el-form-item>
                        </el-col>
                        <el-col :span="6">
                            <el-form-item label="含税" prop="includeTax">
                                <el-checkbox v-model="productPrice.includeTax" @change="handleChangeIncludeTax">
                                </el-checkbox>
                            </el-form-item>
                        </el-col>
                    </el-row>
                </el-form>
            </div>
        </el-card>
        <el-divider></el-divider>
        <el-card class="box-card" shadow="never">
            <div slot="header" class="clearfix">
                <body-toolbar :table="$refs.xTable" @add="handleAddItem" @delete="handleBodyDelete" @fill="handleFill"
                    :status="1"></body-toolbar>
            </div>
            <div class="text item">
                <vxe-table border align="center" show-footer :data="productPrice.items" auto-resize :export-config="{}"
                    resizable ref="xTable" :show-overflow="true" @cell-click="handleCellClick" size="small"
                    :edit-rules="bodyRules" :mouse-config="{ selected: true }" :checkbox-config="{ range: true }"
                    :keyboard-config="{
                        isArrow: true,
                        isDel: false,
                        isEnter: true,
                        isTab: true,
                        isEdit: true,
                    }" :edit-config="{
                        trigger: 'click',
                        mode: 'cell',
                        activeMethod: handleCellEnableEdit,
                    }">
                    <vxe-table-column type="checkbox" width="40" fixed="left"></vxe-table-column>
                    <vxe-table-column type="seq" width="40" fixed="left"></vxe-table-column>
                    <vxe-table-column field="productCode" title="产品代码" align="left" header-align="center" width="120"
                        fixed="left" :edit-render="{
                            attrs: {},
                            enabled: true,
                        }">
                        <template #default="{ row }">
                            <div>
                                {{ row.productCode }}
                            </div>
                        </template>
                        <template #edit="{ row }">
                            <product-select v-model="row.productId"
                                @change="(product) => handleChangeProduct(row, product)"></product-select>
                        </template>
                    </vxe-table-column>
                    <vxe-table-column field="productName" title="产品名称" align="left" header-align="center" width="140"
                        fixed="left">
                        <template #default="{ row }">
                            <div>
                                {{ row.productName }}
                            </div>
                        </template>
                    </vxe-table-column>
                    <vxe-table-column field="productModel" title="规格型号" align="left" header-align="center" width="120"
                        fixed="left">
                        <template #default="{ row }">
                            <div>
                                {{ row.productModel }}
                            </div>
                        </template>
                    </vxe-table-column>
                    <vxe-table-column field="basicUnitId" title="计价单位" align="center" header-align="center" width="120"
                        :edit-render="{
                            attrs: {},
                            autofocus: '.custom-input',
                            enabled: false,
                        }">
                        <template #default="{ row }">
                            <div>
                                {{ row.basicUnitName }}
                            </div>
                        </template>
                    </vxe-table-column>
                    <vxe-table-column field="minQuantity" title="起始数量" align="right" header-align="center" width="120"
                        :edit-render="{
                            attrs: {},
                            autofocus: '.custom-input',
                            enabled: true,
                        }">
                        <template #default="{ row }">
                            <div>
                                {{ row.minQuantity | quantity }}
                            </div>
                        </template>
                        <template #edit="{ row }">
                            <number-input v-model="row.minQuantity" :precision="4" :min="0"></number-input>
                        </template>
                    </vxe-table-column>
                    <vxe-table-column field="maxQuantity" title="截止数量" align="right" header-align="center" width="120"
                        :edit-render="{
                            attrs: {},
                            autofocus: '.custom-input',
                        }">
                        <template #default="{ row }">
                            <div>
                                {{ row.maxQuantity | quantity }}
                            </div>
                        </template>
                        <template #edit="{ row }">
                            <number-input v-model="row.maxQuantity" :precision="4" :min="0"></number-input>
                        </template>
                    </vxe-table-column>

                    <vxe-table-column field="price" title="单价" align="right" header-align="center" width="120"
                        :edit-render="{
                            attrs: {},
                        }">
                        <template #default="{ row }">
                            <div>
                                <span>{{ row.price | price }}</span>
                            </div>
                        </template>
                        <template #edit="{ row }">
                            <number-input v-model="row.price" :precision="4" :min="0"
                                @input="(price) => handleChangePrice(row, price)"></number-input>
                        </template>
                    </vxe-table-column>
                    <vxe-table-column field="taxRateId" title="税率" align="left" header-align="center" width="120"
                        :edit-render="{
                            attrs: {},
                        }">
                        <template #default="{ row }">
                            <div>
                                <span>{{ row.taxRateName }}</span>
                            </div>
                        </template>
                        <template #edit="{ row }">
                            <taxrate-select v-model="row.taxRateId"
                                @change="(taxRate) => handleChangeTaxRate(row, taxRate)"></taxrate-select>
                        </template>
                    </vxe-table-column>
                    <vxe-table-column field="priceIncludeTax" title="含税单价" align="right" header-align="center"
                        width="120" :edit-render="{
                            attrs: {},
                            enabled: false
                        }">
                        <template #default="{ row }">
                            <div>
                                <span>{{ row.priceIncludeTax | price }}</span>
                            </div>
                        </template>
                    </vxe-table-column>
                    <vxe-table-column field="priceExcludeTax" title="不含税单价" align="right" header-align="center"
                        width="120" :edit-render="{
                            attrs: {},
                            enabled: false
                        }">
                        <template #default="{ row }">
                            <div>
                                <span>{{ row.priceExcludeTax | price }}</span>
                            </div>
                        </template>
                    </vxe-table-column>
                    <vxe-table-column field="effectiveDate" title="生效日期" align="right" header-align="center" width="120"
                        :edit-render="{
                            attrs: {},
                            enabled: true
                        }">
                        <template #default="{ row }">
                            <div>
                                <span>{{ row.effectiveDate | datetime }}</span>
                            </div>
                        </template>
                        <template #edit="{ row }">
                            <el-date-picker v-model="row.effectiveDate" type="date" width="120" format="yyyy-MM-dd"
                                value-format="yyyy-MM-dd" :picker-options="pickerOptions"></el-date-picker>
                        </template>
                    </vxe-table-column>
                    <vxe-table-column field="expirationDate" title="失效日期" align="right" header-align="center"
                        width="120" :edit-render="{
                            attrs: {},
                            enabled: true
                        }">
                        <template #default="{ row }">
                            <div>
                                <span>{{ row.expirationDate | datetime }}</span>
                            </div>
                        </template>
                        <template #edit="{ row }">
                            <el-date-picker v-model="row.expirationDate" type="date" format="yyyy-MM-dd"
                                value-format="yyyy-MM-dd" :picker-options="pickerOptions"></el-date-picker>
                        </template>
                    </vxe-table-column>
                </vxe-table>
            </div>
        </el-card>
        <el-drawer direction="rtl" :visible.sync="editAttachmentDrawer" :with-header="false">
            <div v-if="editAttachmentDrawer">
                <attachment-panel :moduleCode="'purchaseProductPrice'" :ownerId="productPrice.id"></attachment-panel>
            </div>
        </el-drawer>
        <print-dialog ref="printPanel" :moduleCode="'purchaseProductPrice'" :ids="[this.id]"></print-dialog>
    </div>
</template>
<script>
import {
    getProductPrice,
    addProductPrice,
    updateProductPrice,
    deleteProductPrice,
} from "@/api/purchase/productPrice";
import { calculatePrice } from "@/utils/document"
import headerToolbar from "@/components/Bar/documentHeaderToolbar.vue";
import bodyToolbar from "@/components/Bar/documentBodyToolbar.vue";
import currencySelect from "@/components/Select/currencySelect.vue";
import supplierSelect from "@/components/Select/supplierSelect.vue";
import attachmentPanel from "@/components/Attachment/index.vue";
import printDialog from "@/components/Print/index.vue";
import unitSelect from "@/components/Select/unitSelect.vue";
import taxrateSelect from "@/components/Select/taxrateSelect.vue";
import numberInput from "@/components/Input/numberInput.vue";
import productSelect from "@/components/Select/productSelect.vue";
export default {
    components: {
        headerToolbar,
        bodyToolbar,
        currencySelect,
        unitSelect,
        supplierSelect,
        attachmentPanel,
        printDialog,
        taxrateSelect,
        numberInput,
        productSelect
    },
    data() {
        return {
            productPrice: {
                id: null,
                code: null,
                name: null,
                supplierId: null,
                includeTax: true,
                currencyId: null,
                items: []
            },
            headerRules: {
                code: [
                    {
                        required: true,
                        message: "请填写编码",
                        trigger: "change",
                    },
                ],
                name: [
                    {
                        required: true,
                        message: "请填写名称",
                        trigger: "change",
                    },
                ],
                currencyId: [
                    {
                        required: true,
                        message: "请选择币别",
                        trigger: "change",
                    },
                ],
            },
            bodyRules: {
                productCode: [{ required: true, message: "请选择产品" }],
                price: [{ required: true, message: "请填写单价" }],
            },
            isModifying: false,
            editAttachmentDrawer: false,
            currentCell: { row: null, column: null },
            pickerOptions: {
                cellClassName: this.setCellClassName
            }
        };
    },
    methods: {
        getData() {
            if (!this.id) {
                this.setDefaultInfo();
                return;
            }
            getProductPrice(this.id).then((res) => {
                this.productPrice = res || {};
            });

        },
        handleRefresh() {
            this.getData();
        },
        handleReturnList() {
            if (this.isModifying) {
                this.$confirm("当前数据为保存，是返回列表?", "提示", {
                    confirmButtonText: "确定",
                    cancelButtonText: "取消",
                    type: "warning",
                })
                    .then(() => {
                        this.$router.push({
                            name: "PurchaseProductPrice",
                        });
                    })
                    .catch(() => { });
            } else {
                this.$router.push({
                    name: "PurchaseProductPrice",
                });
            }
        },
        handleAddItem() {
            let item = this.getDefaultValueItem();

            this.$refs.xTable.insertAt(item, -1);
            this.productPrice.items.push(item);
        },
        handleDelete({ id }) {
            deleteProductPrice(id).then((res) => {
                this.$notify({
                    title: "成功",
                    message: "删除成功",
                    type: "success",
                    position: "bottom-right",
                });
                this.isModifying = false;
                this.handleReturnList();
            });
        },
        async handleSave() {
            await this.validate(this.saveData);
        },
        async validate(callback) {
            const v1 = new Promise((resolve, reject) => {
                this.$refs.form.validate(valid => {
                    if (valid) resolve();
                }, true);
            });

            const v2 = new Promise((resolve, reject) => {

                this.$refs.xTable.validate(true, (errMap) => {
                    if (errMap) {
                        reject();
                    } else {
                        resolve();
                    }
                })
            });

            Promise.all([v1, v2]).then(() => {
                callback(true);
            });
        },
        saveData() {
            let items = this.getValidItems();

            this.productPrice.items = items;
            if (this.id) {
                updateProductPrice(this.productPrice).then((res) => {
                    if (res) {
                        this.productPrice = res;
                        this.$notify({
                            title: "成功",
                            message: "保存成功",
                            type: "success",
                            position: "bottom-right",
                        });
                    }
                });
            } else {
                addProductPrice(this.productPrice).then((res) => {
                    if (res) {
                        this.productPrice = res;
                        this.$notify({
                            title: "成功",
                            message: "保存成功",
                            type: "success",
                            position: "bottom-right",
                        });
                    }
                });
            }
        },
        getValidItems() {
            let items = this.productPrice.items.filter(x => x.productId);

            if (!items)
                return [];

            for (let i = 0; i < items.length; i++) {
                items[i].index = i + 1;
            }
            return items;
        },
        handleCellEnableEdit({ row, rowIndex, column, columnIndex }) {
            return true;
        },
        handleCellClick({ row, rowIndex, $rowIndex, column, columnIndex, $columnIndex }) {
            this.currentCell = { row: row, column: column }
        },
        getDefaultValueItem() {
            return {
                id: null,
                productId: null,
                productCode: null,
                productName: null,
                minQuantity: null,
                maxQuantity: null,
                price: null,
                priceIncludeTax: null,
                priceExcludeTax: null,
                taxRateId: null,
                taxRateName: null,
                taxRateValue: null,
                basicUnitId: null,
                basicUnitName: null,
                basicQuantity: null,
                effectiveDate: new Date(),
                expirationDate: new Date()
            };
        },
        handleChangeCurrency(currency) {
            this.productPrice.currencyName = currency.currencyName;
            let items = this.productPrice.items;
            if (!items || items.length == 0)
                return;
            items.forEach(item => {
                calculatePrice(this.productPrice.includeTax, item);
            })

        },
        handleChangeExchangeRate(item, value) {
            calculatePrice(this.productPrice.includeTax, item);
        },
        handleChangeIncludeTax() {
            let items = this.productPrice.items;
            if (!items || items.length == 0)
                return;
            items.forEach(item => {
                calculatePrice(this.productPrice.includeTax, item);
            })
        },
        handleChangeProduct(item, product) {
            if (!product)
                return;
            item.productName = product.name;
            item.productCode = product.code;
            item.productModel = product.model;
            item.basicUnitId = product.basicUnitId;
            item.basicUnitName = product.basicUnitName;

            this.setProductDefaultInfo(item, product.id);
        },
        handleSupplierChange(supplier) {
            this.productPrice.supplierName = supplier.name;
        },
        handleChangeTaxRate(item, taxRate) {
            item.taxRateName = taxRate.name;
            item.taxRateValue = taxRate.rate;
            calculatePrice(this.productPrice.includeTax, item);
        },
        handleChangePrice(item, price) {
            calculatePrice(this.productPrice.includeTax, item);
        },
        setDefaultInfo() {
            if (this.productPrice.items && this.productPrice.items.length > 0) return;
            //默认插四行数据
            for (let i = 0; i < 1; i++) {
                let item = this.getDefaultValueItem();
                this.productPrice.items.push(item);
            }
        },
        handleAttachment() {
            this.editAttachmentDrawer = true;
        },
        handlePrint() {
            this.$refs.printPanel.showDialog();
        },
        handleBodyDelete({ ids, rows }) {
            if (!rows || rows.length == 0) return;
            this.productPrice.items.remove(rows);
        },
        handleFill() {
            if (!this.currentCell || !this.currentCell.row || this.productPrice.items.length == 0)
                return;
            let row = this.currentCell.row;
            let column = this.currentCell.column;

            //有些字段不允许批量填充
            if (column.property == "productCode") {
                return;
            }

            this.productPrice.items.forEach(item => {
                let columnNames = [column.property];

                if (column.property == "taxRateId") {
                    columnNames.push("taxRateName")
                }
                columnNames.forEach(columnName => {
                    item[columnName] = row[columnName];
                })

            })
        },
        setProductDefaultInfo(item, productId) {

        },
        setCellClassName() {
            return "vxe-table–ignore-clear";
        }
    },
    mounted() {
        this.$nextTick(() => {
            this.getData();
        });
    },
    computed: {
        id() {
            return this.$route.query.id;
        }
    },
    watch: {},
};
</script>
<style scoped></style>